<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>scrollIntoView</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .box {
        height: 500px;
      }
      .color1 {
        background-color: orange;
      }
      .color2 {
        background-color: aquamarine;
      }
      .color3 {
        background-color: blue;
      }
      .color4 {
        background-color: chartreuse;
      }
      .color5 {
        background-color: cornflowerblue;
      }
      .btn {
        position: fixed;
        bottom: 100px;
        right: 20px;
        padding: 10px;
        border-radius: 10px;
        border: 0;
        cursor: pointer;
      }
      .btn2 {
        bottom: 20px;
      }
      ul {
        height: 1000px;
        overflow-y: scroll;
      }
      li {
        text-align: left;
        height: 300px;
        line-height: 100px;
        padding-left: 20px;
      }
    </style>
  </head>
  <body>
    <!-- 示例1 -->
    <div class="box color1"></div>
    <div class="box color2"></div>
    <div class="box color3"></div>
    <div class="box color4"></div>
    <div class="box color5"></div>
    <button class="btn">点我演示示例1</button>
    <button class="btn btn2">点我演示示例2</button>
    <!-- 示例2 -->
    <ul>
      <li>C</li>
      <li>Java</li>
      <li>Python</li>
      <li>C++</li>
      <li>C#</li>
      <li>Go</li>
      <li>Visual Basic</li>
      <li>JavaScript</li>
      <li>PHP</li>
      <li>SQL</li>
      <li>R</li>
      <li>Swift</li>
      <li class="special">JavaScript</li>
      <li>MATLAB</li>
      <li>Assembly language</li>
      <li>Ruby</li>
      <li>PL/SQL</li>
      <li>Classic Visual Basic</li>
      <li>Perl</li>
      <li>Scratch</li>
      <li>Objective-C</li>
    </ul>
  </body>
  <script>
    const body = document.body;
    let flag = true;
    const btn = document.querySelector(".btn");
    const btn2 = document.querySelector(".btn2");
    /**
     * Element.scrollIntoView();
     * scrollIntoView() 方法会滚动元素的父容器，使被调用 scrollIntoView() 的元素对用户可见。
     * scrollIntoView() 方法来将元素滚动到视口/父容器的指定位置
     */

    // 示例1
    btn.addEventListener("click", function () {
      if (flag) {
        // 从顶部平衡动画回到底部
        body.scrollIntoView({ behavior: "smooth", block: "end" });
        flag = false;
      } else {
        // 从底部平衡动画回到顶部
        body.scrollIntoView({ behavior: "smooth", block: "start" });
        flag = true;
      }
    });
    // 示例2
    let el = document.querySelector(".special");

    btn2.addEventListener("click", function () {
      el.scrollIntoView(true, {
        behavior: "smooth",
      });
    });
  </script>
</html>
